package com.vb.ecm.web.custom.barcode;

/**  File Name           : GenerateBarcodePages
 *  Description         : Contains the Implementation class to generate barcode pdf page.
 *  Created On          : 5 Nov 2012
 *  Modification History : None
 *  barcode.jar, barbecue-1.5-beta1.jar, barcode4j-2.0.jar
 */

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.log4j.Logger;

import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSysObject;
import com.documentum.fc.common.DfException;
import com.documentum.web.common.ArgumentList;
import com.documentum.web.form.control.Label;
import com.documentum.web.form.control.TextArea;
import com.documentum.web.form.control.databound.Datagrid;
import com.documentum.web.formext.component.Component;

@SuppressWarnings("serial")
public class GenerateBarcodePages extends Component {

	Datagrid commentsGrid = null;
	String barcodeValueTA = null;
	String[] tempValues = null;
	String barcodeValue = null;
	String barcodeValue2 = null;
	String barcodeValue3 = null;
	String barcodeValue4 = null;
	String barcodeValue5 = null;
	String snv1 = null;
	String snv2 = null;
	String snv3 = null;
	String snv4 = null;
	String snv5 = null;
	IDfSession session = null;
	TextArea barcodeValueTextArea = null;
	ArrayList<GenerateBarcodePagesBean> dataBeanList = new ArrayList<GenerateBarcodePagesBean>();

	private static final Logger LOGGER = Logger.getLogger(GenerateBarcodePages.class);

	public void onInit(final ArgumentList arg) {
		IDfCollection collection = null;
		try {
			LOGGER.debug("Enter into onInit()");
			Label errorMsg = (Label) getControl("error_msg", com.documentum.web.form.control.Label.class);
			errorMsg.setLabel("");
			LOGGER.debug("Exit from onInit()");
		} catch (Exception e) {
			LOGGER.error("error in onInit :" + e);
			e.printStackTrace();
		} finally {
			closeCollection(collection);
		}
	}

	public boolean onCommitChanges() {
		try {
			LOGGER.debug("Enter into onCommitChanges()");
			session = getDfSession();
			ServletContext servletcontext = getPageContext().getServletContext();
			HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();

			barcodeValueTextArea = (TextArea) getControl("BarcodeTA", com.documentum.web.form.control.TextArea.class);
			barcodeValueTA = barcodeValueTextArea.getValue();
			System.out.println("barcodeValue:" + barcodeValueTA);
			if (barcodeValueTA.contains(";")) {
				tempValues = barcodeValueTA.split(GenerateBarcodePagesConstants.BARCODE_DELIMITER);
			} else {
				barcodeValue = barcodeValueTA;
				snv1 = "1";
			}

			try {
				barcodeValue = tempValues[0];
				snv1 = "1";
				barcodeValue2 = tempValues[1];
				snv2 = "2";
				barcodeValue3 = tempValues[2];
				snv3 = "3";
				barcodeValue4 = tempValues[3];
				snv4 = "4";
				barcodeValue5 = tempValues[4];
				snv5 = "5";
			} catch (Exception e) {
				// TODO Auto-generated catch block
				// LOGGER.error("error in onCommitChanges :"+e);
				// e.printStackTrace();
			}

			dataBeanList.add(produce(snv1, barcodeValue, snv2, barcodeValue2, snv3, barcodeValue3, snv4, barcodeValue4, snv5, barcodeValue5, "logo"));

			System.out.println("Data List size: " + dataBeanList.size());
			String reportObjectID = generateJasperReport(dataBeanList, session, barcodeValue);
			LOGGER.debug("Record Created Successfully Report=" + reportObjectID);
			LOGGER.debug("Exit from onCommitChanges()");
		} catch (Exception e) {
			LOGGER.error("error in onCommitChanges :" + e);
			e.printStackTrace();
			Label errorMsg = (Label) getControl("error_msg", com.documentum.web.form.control.Label.class);
			errorMsg.setLabel("Error in Creating Barcode Pages:" + e);
			// setComponentPage("start");
			return false;
		}
		return true;
	}

	/*
	 * SETTING ALL PROPERTIES INTO REPORT BEAN OBJECT
	 */

	private GenerateBarcodePagesBean produce(String snv1, String barcodev, String snv2, String barcodev2, String snv3, String barcodev3, String snv4, String barcodev4,
			String snv5, String barcodev5, String vietinbanklogo) throws DfException {
		GenerateBarcodePagesBean reportBean = new GenerateBarcodePagesBean();
		reportBean.setSnv1(snv1);
		reportBean.setBarcodev(barcodev);
		reportBean.setSnv2(snv2);
		reportBean.setBarcodev2(barcodev2);
		reportBean.setSnv3(snv3);
		reportBean.setBarcodev3(barcodev3);
		reportBean.setSnv4(snv4);
		reportBean.setBarcodev4(barcodev4);
		reportBean.setSnv5(snv5);
		reportBean.setBarcodev5(barcodev5);
		reportBean.setVietinbanklogo(vietinbanklogo);
		return reportBean;
	}

	/*
	 * Method for creating a pdf typed report and imported into repository
	 * contains Jasper related code
	 */

	public String generateJasperReport(ArrayList<GenerateBarcodePagesBean> dataBeanList, IDfSession session, String barcodeValue) throws Exception {

		LOGGER.debug("Enter into generateJasperReport()");
		String pdfName = "";

		// code for jasper reports
		JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataBeanList, false);
		Map parameters = new HashMap();
		// File reportTemplateJRXMLFile = new File(reportURL);
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("com/vb/ecm/web/custom/barcode/GenerateBarcodePages.jrxml");
		// InputStream inputStream = new
		// FileInputStream(reportTemplateJRXMLFile);
		// InputStream inputStream =
		// servletcontext.getResourceAsStream(reportURL);
		JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
		JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);		
		// storing report into repository
		ByteArrayOutputStream objByteArrayOutputStream = new ByteArrayOutputStream();
		JasperExportManager.exportReportToPdfStream(jasperPrint, objByteArrayOutputStream);		 
		//JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/Temp/BarcodePages/test.pdf");
		//Document document = new Document(PageSize.A4, 36, 72, 108, 180);
		//PdfWriter.getInstance(document,new FileOutputStream("C:/Temp/Barcodepages/pdfFile.pdf"));
		//document.open();
		//document.add(new Paragraph(jasperPrint.toString()));
		IDfSysObject sysObj = (IDfSysObject) session.newObject("dm_document");
		System.out.println("final pdf name: " + barcodeValue);
		sysObj.setObjectName(barcodeValue);
		sysObj.setContentType("pdf");
		sysObj.link(GenerateBarcodePagesConstants.REPORT_STORING_LOCATION);
		sysObj.setContent(objByteArrayOutputStream);
		sysObj.save();
		LOGGER.debug("Exit from generateJasperReport()");
		return barcodeValue;
	}

	public void closeCollection(IDfCollection collection) {
		if (collection != null) {
			try {
				collection.close();
			} catch (final DfException e) {
				LOGGER.error("Exception in closeCollection() :" + e);
				e.printStackTrace();
			}
		}
	}
}
